package com.googlecode.ozonbooksfinder.matefinder.actions
{
	import com.asfusion.mate.actionLists.IScope;
	import com.asfusion.mate.actionLists.ServiceHandlers;
	import com.asfusion.mate.actions.IAction;
	import com.asfusion.mate.actions.builders.ServiceInvoker;
	import com.asfusion.mate.core.ISmartObject;
	import com.asfusion.mate.events.UnhandledFaultEvent;
	
	import mx.rpc.events.FaultEvent;
	
	import ru.ozon.ItemDetailResultEvent;
	import ru.ozon.OzonWebSvc;

	public class ItemDetailsServiceInvoker extends ServiceInvoker implements IAction
	{
		private var _bookId:Object;
		public function get bookId():Object
		{
			return _bookId;
		}
		public function set bookId(value:Object):void
		{
			_bookId = value;
		}
		
		/**
		 * @inheritDoc
		 */
		override protected function prepare(scope:IScope):void
		{
			if (!currentInstance)
			{ 
				currentInstance = new OzonWebSvc ();
			}
		}
		
		/**
		 * @inheritDoc
		 */
		override protected function run(scope:IScope):void
		{
			var webserviceInstance:OzonWebSvc = currentInstance;
			
			var realBookId:Number;
			if(bookId is ISmartObject)
			{
				realBookId = 
					Number (ISmartObject(bookId).getValue(scope));
			}
			else
			{
				realBookId = Number (bookId);
			}
			
			token = webserviceInstance.itemDetail(realBookId);
			
			scope.lastReturn = token;
		}
		
		/**
		 * @inheritDoc
		 */
		override protected function complete(scope:IScope):void
		{
			innerHandlersDispatcher = currentInstance;
			
			if(resultHandlers && resultHandlers.length > 0)
			{
				var resultHandlersInstance:ServiceHandlers = createInnerHandlers(scope,  
											ItemDetailResultEvent.ItemDetail_RESULT, 
											resultHandlers, 
											WebServiseHanglers)  as ServiceHandlers;
				resultHandlersInstance.token = token;
				resultHandlersInstance.validateNow();
			}
			if( (faultHandlers && faultHandlers.length > 0) || 
				scope.dispatcher.hasEventListener(UnhandledFaultEvent.FAULT))
			{
				var faultHandlersInstance:ServiceHandlers = createInnerHandlers(scope,  
											FaultEvent.FAULT, 
											faultHandlers, 
											WebServiseHanglers)  as ServiceHandlers; 
				faultHandlersInstance.token = token;
				faultHandlersInstance.validateNow();
			}
		}
	}
}